class Player extends AcGameObject {
    constructor(playground, x, y, radius, color, speed, is_me) {
        super();
        this.playground = playground;
        this.ctx = this.playground.game_map.ctx;
        this.x = x;
        this.y = y;
        this.vx = 0;
        this.vy = 0;
        this.damage_x = 0;
        this.damage_y = 0;
        this.damage_speed = 0;
        this.move_length = 0;
        this.radius = radius;
        this.color = color;
        this.speed = speed;
        this.is_me = is_me;
        this.eps = 0.1;
        this.friction = 0.9;
        this.spent_time = 0;

        this.cur_skill = null;

        // 添加移动端摇杆相关属性
        this.is_mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        this.joystick = null;
        if (this.is_mobile && this.is_me) {
            this.create_joystick();
        }

        this.img = new Image();
        if (this.is_me) {
        this.img.src = "/static/image/menu/ground.png";
        }else{
            this.img.src = "/static/image/menu/goutou.png";
        }



    }

    start() {
        if (this.is_me) {
            this.add_listening_events();
        } else {
            let tx = Math.random() * this.playground.width;
            let ty = Math.random() * this.playground.height;
            this.move_to(tx, ty);
        }
    }

    // 创建虚拟摇杆
    create_joystick() {
        // 创建摇杆容器
        this.joystick = $(`            <div id="mobile-joystick" style="
                position: fixed;
                bottom: 50px;
                left: 50px;
                width: 100px;
                height: 100px;
                border: 2px solid rgba(255, 255, 255, 0.5);
                border-radius: 50%;
                background: rgba(0, 0, 0, 0.3);
                display: none;
                z-index: 1000;
            ">
                <div id="joystick-handle" style="
                    position: absolute;
                    width: 40px;
                    height: 40px;
                    background: rgba(255, 255, 255, 0.7);
                    border-radius: 50%;
                    top: 30px;
                    left: 30px;
                "></div>
            </div>
        `);

        // 创建射击按钮
        this.shoot_button = $(`            <div id="shoot-button" style="
                position: fixed;
                bottom: 50px;
                right: 50px;
                width: 80px;
                height: 80px;
                background: rgba(255, 0, 0, 0.5);
                border-radius: 50%;
                display: none;
                z-index: 1000;
                text-align: center;
                line-height: 80px;
                color: white;
                font-weight: bold;
            ">
                射击
            </div>
        `);

        this.playground.$playground.append(this.joystick);
        this.playground.$playground.append(this.shoot_button);

        this.bind_joystick_events();
    }

    // 显示摇杆
    show_joystick() {
        if (this.joystick) {
            this.joystick.show();
        }
        if (this.shoot_button) {
            this.shoot_button.show();
        }
    }

    // 隐藏摇杆
    hide_joystick() {
        if (this.joystick) {
            this.joystick.hide();
        }
        if (this.shoot_button) {
            this.shoot_button.hide();
        }
    }
    add_listening_events() {
        let outer = this;
        this.playground.game_map.$canvas.on("contextmenu", function () {
            return false;
        });
         // 检查是否为移动端
        const is_mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

        if (is_mobile && this.is_me) {
            // 移动端触摸事件
            this.playground.game_map.$canvas.on('touchstart', function (e) {
                e.preventDefault();
                // 显示摇杆和按钮
                outer.show_joystick();

                if (e.targetTouches.length > 0) {
                    const rect = outer.ctx.canvas.getBoundingClientRect();
                    let touch = e.targetTouches[0];
                    // 如果不是在摇杆区域，则移动角色
                    if (!(touch.clientX > 50 && touch.clientX < 150 &&
                        touch.clientY > window.innerHeight - 150 && touch.clientY < window.innerHeight - 50)) {
                        outer.move_to(touch.clientX - rect.left, touch.clientY - rect.top);
                    }
                }
            });
        } else {
            this.playground.game_map.$canvas.mousedown(function (e) {
                const rect = outer.ctx.canvas.getBoundingClientRect();
                if (e.which === 3) {
                    outer.move_to(e.clientX - rect.left, e.clientY - rect.top);
                } else if (e.which === 1) {
                    if (outer.cur_skill === "fireball") {
                        outer.shoot_fireball(e.clientX - rect.left, e.clientY - rect.top);
                    }

                    outer.cur_skill = null;
                }
            });
        }
        $(window).keydown(function(e) {
            if (e.which === 81) {  // q
                outer.cur_skill = "fireball";
                return false;
            }
        });
    }


     // 添加移动端触摸事件
    bind_joystick_events() {
        if (!this.joystick || !this.shoot_button) return;

        let outer = this;
        let joystick_active = false;
        let joystick_center_x = 0;
        let joystick_center_y = 0;
        let handle = this.joystick.find('#joystick-handle')[0];
        let max_distance = 30;

        // 摇杆触摸开始
        this.joystick.on('touchstart', function(e) {
            e.preventDefault();
            console.log("Joystick touch start");
            if (e.targetTouches.length > 0) {
                joystick_active = true;
                let touch = e.targetTouches[0];
                joystick_center_x = touch.clientX;
                joystick_center_y = touch.clientY;
            }
        });

        // 摇杆拖动处理
        this.joystick.on('touchmove', function(e) {
            e.preventDefault();
            console.log("Joystick touch move");
            if (joystick_active && e.targetTouches.length > 0) {
                let touch = e.targetTouches[0];
                let dx = touch.clientX - joystick_center_x;
                let dy = touch.clientY - joystick_center_y;
                let distance = Math.sqrt(dx * dx + dy * dy);
                console.log(1111);

                if (distance > max_distance) {
                    dx = dx * max_distance / distance;
                    dy = dy * max_distance / distance;
                }

                handle.style.left = (30 + dx) + 'px';
                handle.style.top = (30 + dy) + 'px';

                // 根据摇杆位置计算移动方向
                if (distance > 5) {
                    let move_x = outer.x + dx * 3;
                    let move_y = outer.y + dy * 3;
                    outer.move_to(move_x, move_y);
                }
            }
        });

        // 摇杆触摸结束
        this.joystick.on('touchend touchcancel', function(e) {
            e.preventDefault();
            console.log("Joystick touch end");
            joystick_active = false;
            // 重置摇杆位置
            handle.style.left = '30px';
            handle.style.top = '30px';
        });

        // 射击按钮事件
        this.shoot_button.on('touchstart', function(e) {
            e.preventDefault();
            console.log("Shoot button pressed");
            // 在移动端，我们直接触发火球技能，无需先按Q键
            outer.cur_skill = "fireball"; // 设置当前技能为火球

            if (outer.cur_skill === "fireball") {
                console.log("Shoot Fireball");
                // 在玩家前方发射火球
                let tx = outer.x + outer.vx * 100;
                let ty = outer.y + outer.vy * 100;
                // 如果没有移动方向，则在角色前方发射
                if (Math.abs(outer.vx) < 0.01 && Math.abs(outer.vy) < 0.01) {
                    // 默认向前方发射（比如向右）
                    tx = outer.x + 100;
                    ty = outer.y;
                }
                outer.shoot_fireball(tx, ty);
            }
            outer.cur_skill = null; // 释放技能
        });
    }
    shoot_fireball(tx, ty) {
        let x = this.x, y = this.y;
        let radius = this.playground.height * 0.01;
        let angle = Math.atan2(ty - this.y, tx - this.x);
        let vx = Math.cos(angle), vy = Math.sin(angle);
        let color = "orange";
        let speed = this.playground.height * 0.4;
        let move_length = this.playground.height * 1;
        new FireBall(this.playground, this, x, y, radius, vx, vy, color, speed, move_length, this.playground.height * 0.01);
    }

    get_dist(x1, y1, x2, y2) {
        let dx = x1 - x2;
        let dy = y1 - y2;
        return Math.sqrt(dx * dx + dy * dy);
    }

    move_to(tx, ty) {
        this.move_length = this.get_dist(this.x, this.y, tx, ty);
        let angle = Math.atan2(ty - this.y, tx - this.x);
        this.vx = Math.cos(angle);
        this.vy = Math.sin(angle);
    }

    is_attacked(angle, damage) {
        for (let i = 0; i < 20 + Math.random() * 10; i ++ ) {
            let x = this.x, y = this.y;
            let radius = this.radius * Math.random() * 0.1;
            let angle = Math.PI * 2 * Math.random();
            let vx = Math.cos(angle), vy = Math.sin(angle);
            let color = this.color;
            let speed = this.speed * 10;
            let move_length = this.radius * Math.random() * 5;
            new Particle(this.playground, x, y, radius, vx, vy, color, speed, move_length);
        }
        this.radius -= damage;
        if (this.radius < 10) {
            this.destroy();
            return false;
        }
        this.damage_x = Math.cos(angle);
        this.damage_y = Math.sin(angle);
        this.damage_speed = damage * 100;
        this.speed *= 0.85;
    }

    update() {
        this.spent_time += this.timedelta / 1000;
        if (!this.is_me && this.spent_time > 4 && Math.random() < 1 / 300.0) {
            let player = this.playground.players[Math.floor(Math.random() * this.playground.players.length)];
            let tx = player.x + player.speed * this.vx * this.timedelta / 1000 * 0.3;
            let ty = player.y + player.speed * this.vy * this.timedelta / 1000 * 0.3;
            this.shoot_fireball(tx, ty);
        }

        if (this.damage_speed > 10) {
            this.vx = this.vy = 0;
            this.move_length = 0;
            this.x += this.damage_x * this.damage_speed * this.timedelta / 1000;
            this.y += this.damage_y * this.damage_speed * this.timedelta / 1000;
            this.damage_speed *= this.friction;
        } else {
            if (this.move_length < this.eps) {
                this.move_length = 0;
                this.vx = this.vy = 0;
                if (!this.is_me) {
                    let tx = Math.random() * this.playground.width;
                    let ty = Math.random() * this.playground.height;
                    this.move_to(tx, ty);
                }
            } else {
                let moved = Math.min(this.move_length, this.speed * this.timedelta / 1000);
                this.x += this.vx * moved;
                this.y += this.vy * moved;
                this.move_length -= moved;
            }
        }
        this.render();
    }

    render() {
        this.ctx.save();
        this.ctx.beginPath();
        this.ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
        this.ctx.stroke();
        this.ctx.clip();
        this.ctx.drawImage(this.img, this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
        this.ctx.restore();
    }

    on_destroy() {
        // 销毁时隐藏摇杆
        if (this.is_me && this.joystick) {
            this.hide_joystick();
        }
        for (let i = 0; i < this.playground.players.length; i ++ ) {
            if (this.playground.players[i] === this) {
                this.playground.players.splice(i, 1);
                break;
            }
        }
    }
}
